import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_1/global.dart';
import 'package:fluttertoast/fluttertoast.dart';

class SimpleFormTest extends StatefulWidget {
  @override
  _SimpleFormTestState createState() => _SimpleFormTestState();
}

class CheckboxData {
  String name;
  bool isCheck;

  CheckboxData({
    required this.name,
    this.isCheck = false,
  });
}

class _SimpleFormTestState extends State<SimpleFormTest> {
  // 标题
  Widget _titleBuilder(String title) {
    final BorderSide thinBorder = BorderSide(
      width: 2,
      color: Theme.of(context).primaryColor,
    );

    final BorderSide boldBorder = BorderSide(
      width: 6,
      color: Theme.of(context).primaryColor,
    );

    return Container(
      height: 40,
      margin: EdgeInsets.symmetric(vertical: 5, horizontal: 8),
      padding: EdgeInsets.only(left: 6),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          top: thinBorder,
          right: thinBorder,
          bottom: thinBorder,
          left: boldBorder,
        ),
      ),
      child: Text(title),
    );
  }

  // DropdownButton

  ListTileControlAffinity _controlAffinity = ListTileControlAffinity.platform;

  Widget _dropdownButtonBuilder() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: Row(
        children: [
          Text('ListTile 样式：'),
          Expanded(
            flex: 1,
            child: DropdownButton<ListTileControlAffinity>(
              items: [
                DropdownMenuItem(
                  child: Text('platform'),
                  value: ListTileControlAffinity.platform,
                ),
                DropdownMenuItem(
                  child: Text('leading'),
                  value: ListTileControlAffinity.leading,
                ),
                DropdownMenuItem(
                  child: Text('trailing'),
                  value: ListTileControlAffinity.trailing,
                ),
              ],
              value: _controlAffinity,
              onChanged: (value) => setState(() {
                _controlAffinity = value!;
              }),
            ),
          ),
        ],
      ),
    );
  }

  // Checkbox
  bool _isCheck = false;

  List<CheckboxData> _checkboxDatas = [
    CheckboxData(
      name: '苹果',
      isCheck: false,
    ),
    CheckboxData(
      name: '香蕉',
      isCheck: false,
    ),
    CheckboxData(
      name: '喵咪',
      isCheck: false,
    ),
  ];

  bool _isCheckAll = false;

  List<Widget> _checkboxBuilder() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Checkbox(
            value: true,
            tristate: true,
            onChanged: (val) {},
          ),
          Checkbox(
            value: null,
            tristate: true,
            onChanged: null,
          ),
          Checkbox(
            value: _isCheck,
            activeColor: Colors.red,
            onChanged: (value) => setState(() {
              _isCheck = value ?? false;
            }),
          ),
        ],
      ),
      ...List.generate(
        _checkboxDatas.length,
        (index) {
          CheckboxData data = _checkboxDatas[index];
          return CheckboxListTile(
            title: Text(data.name),
            secondary: Icon(Icons.edit),
            value: data.isCheck,
            controlAffinity: _controlAffinity,
            onChanged: (value) => setState(() {
              data.isCheck = value!;
              // 判断是否全选
              _isCheckAll = _checkboxDatas.every((element) => element.isCheck);
            }),
          );
        },
      ),
      CheckboxListTile(
        title: Text('全选'),
        value: _isCheckAll,
        controlAffinity: _controlAffinity,
        onChanged: (value) => setState(() {
          _isCheckAll = value!;
          _checkboxDatas.forEach((element) {
            element.isCheck = _isCheckAll;
          });
        }),
      ),
    ];
  }

  // Radio
  int _selectedIndex = 0;

  List<Widget> _radioBuilder() {
    return [
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          ...List.generate(
            3,
            (index) => Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Radio<int>(
                  value: index,
                  groupValue: _selectedIndex,
                  onChanged: (value) => setState(() {
                    _selectedIndex = value!;
                  }),
                ),
                Text('$index'),
              ],
            ),
          ),
        ],
      ),
      ...List.generate(
        3,
        (index) => RadioListTile<int>(
          title: Text('$index'),
          value: index,
          groupValue: _selectedIndex,
          controlAffinity: _controlAffinity,
          onChanged: (value) => setState(() {
            _selectedIndex = value!;
          }),
        ),
      ),
    ];
  }

  // Slider

  double _sliderValue = 0;

  RangeValues _rangeValues = RangeValues(20, 80);

  List<Widget> _sliderBuilder() {
    return [
      Slider(
        value: _sliderValue,
        min: 0,
        max: 100,
        onChanged: (value) => setState(() {
          _sliderValue = value.roundToDouble();
        }),
      ),
      Slider(
        value: _sliderValue,
        inactiveColor: Colors.red,
        activeColor: Colors.green,
        min: 0,
        max: 100,
        divisions: 10,
        label: '当前：$_sliderValue',
        onChanged: (value) => setState(() {
          _sliderValue = value.roundToDouble();
        }),
      ),
      RangeSlider(
        values: _rangeValues,
        min: 0,
        max: 100,
        divisions: 10,
        labels: RangeLabels(
          '起始值：${_rangeValues.start.round()}',
          '终值：${_rangeValues.end.round()}',
        ),
        onChanged: (value) => setState(() {
          _rangeValues = value;
        }),
      ),
      RangeSlider(
        values: RangeValues(30, 70),
        min: 0,
        max: 100,
        onChanged: null,
      ),
    ];
  }

  // Switch

  bool _isSwitchCheck = false;

  List<Widget> _switchBuilder() {
    return [
      Container(
        padding: EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: [
            Switch(
              value: _isSwitchCheck,
              onChanged: (value) => setState(() {
                _isSwitchCheck = value;
              }),
            ),
            Switch(
              value: _isSwitchCheck,
              onChanged: null,
            ),
            Switch.adaptive(
              value: _isSwitchCheck,
              activeColor: Colors.red,
              inactiveTrackColor: Colors.green,
              inactiveThumbColor: Colors.yellow,
              onChanged: (value) => setState(() {
                _isSwitchCheck = value;
              }),
            ),
            CupertinoSwitch(
              value: _isSwitchCheck,
              activeColor: Colors.blue,
              onChanged: (value) => setState(() {
                _isSwitchCheck = value;
              }),
            ),
          ],
        ),
      ),
      SwitchListTile(
        value: _isSwitchCheck,
        title: Text('是否可编辑'),
        secondary: Icon(Icons.edit),
        controlAffinity: _controlAffinity,
        onChanged: (value) => setState(() {
          _isSwitchCheck = value;
        }),
      ),
    ];
  }

  // TextField

  TextEditingController _editingController = TextEditingController();
  String _inputVal = '';

  TextEditingController _editingController1 = TextEditingController();

  FocusNode _focusNode1 = FocusNode();
  FocusNode _focusNode2 = FocusNode();

  @override
  void initState() {
    super.initState();

    _focusNode1.addListener(() {
      Fluttertoast.cancel();
      if (_focusNode1.hasFocus) {
        Fluttertoast.showToast(msg: 'FocusNode1 获取焦点');
      } else {
        Fluttertoast.showToast(msg: 'FocusNode1 失去焦点');
      }
    });

    _focusNode2.addListener(() {
      Fluttertoast.cancel();
      if (_focusNode2.hasFocus) {
        Fluttertoast.showToast(msg: 'FocusNode2 获取焦点');
      } else {
        Fluttertoast.showToast(msg: 'FocusNode2 失去焦点');
      }
    });
  }

  Widget _textFieldBuilder() {
    _editingController1.text = 'fanzhiliang';
    _editingController1.selection = TextSelection(
      baseOffset: 3,
      extentOffset: _editingController1.text.length - 5,
    );

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 最大可输入行数
          TextField(
            maxLines: 3,
            decoration: InputDecoration(
              labelText: '最大可输入行数',
            ),
          ),
          SizedBox(height: 10),
          // 键盘输入模式
          TextField(
            keyboardType: TextInputType.number,
            onChanged: (value) => print(value),
            decoration: InputDecoration(
              icon: Icon(Icons.text_fields),
              labelText: 'labelText 键盘',
              hintText: 'hintText 输入',
              helperText: 'helperText 模式',
            ),
          ),
          SizedBox(height: 10),
          // 设置边框
          TextField(
            decoration: InputDecoration(
              labelText: '设置边框',
              // 下划线边框
              border: UnderlineInputBorder(),
              enabledBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.green),
              ),
              focusedBorder: UnderlineInputBorder(
                borderSide: BorderSide(color: Colors.yellow),
              ),
              // 完整边框
              // border: OutlineInputBorder(
              //   borderRadius: BorderRadius.circular(5),
              // ),
              // 无边框
              // border: InputBorder.none,
            ),
          ),
          SizedBox(height: 10),
          // 颜色
          TextField(
            maxLength: 20,
            style: TextStyle(
              fontSize: 20,
              color: Colors.blue,
            ),
            cursorColor: Colors.red,
            // cursorRadius: Radius.circular(20),
            // cursorWidth: 40,
            decoration: InputDecoration(
              isDense: true,
              counterText: '',
              border: OutlineInputBorder(),
              focusedBorder: OutlineInputBorder(
                borderSide: BorderSide(color: Colors.tealAccent),
                borderRadius: BorderRadius.circular(5),
              ),
              filled: true,
              fillColor: Colors.tealAccent,
              hintText: 'hintText',
              hintStyle: TextStyle(color: Colors.pink[900]),
              prefixIcon: Icon(Icons.label),
              suffixIcon: Icon(Icons.list),
            ),
          ),
          SizedBox(height: 10),
          // 键盘完成文字样式
          TextField(
            decoration: InputDecoration(
              labelText: '键盘完成文字样式',
            ),
            textInputAction: TextInputAction.search,
          ),
          SizedBox(height: 10),
          // 控制输入内容
          TextField(
            controller: _editingController,
            decoration: InputDecoration(
              labelText: '控制输入内容',
            ),
          ),
          ElevatedButton(
            child: Text('点击输入123'),
            onPressed: () {
              _editingController.text = '123';
            },
          ),
          // 获取输入内容
          TextField(
            controller: _editingController,
            decoration: InputDecoration(
              labelText: '获取输入内容',
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ElevatedButton(
                child: Text('获取'),
                onPressed: () {
                  setState(() {
                    _inputVal = _editingController.text;
                  });
                },
              ),
              Text(_inputVal),
            ],
          ),
          SizedBox(height: 10),
          // 焦点
          TextField(
            controller: _editingController1,
          ),
          TextField(
            focusNode: _focusNode1,
            decoration: InputDecoration(
              labelText: 'FocusNode1',
            ),
          ),
          TextField(
            focusNode: _focusNode2,
            decoration: InputDecoration(
              labelText: 'FocusNode2',
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ElevatedButton(
                child: Text('让FocusNode2获取焦点'),
                onPressed: () {
                  FocusScopeNode focusScopeNode = FocusScope.of(context);
                  focusScopeNode.requestFocus(_focusNode2);
                },
              ),
              ElevatedButton(
                child: Text('全部失去焦点'),
                onPressed: () {
                  // _focusNode1.unfocus();
                  // _focusNode2.unfocus();

                  // FocusScopeNode focusScopeNode = FocusScope.of(context);
                  // focusScopeNode.unfocus();

                  Global.routerUtils.unfocus();
                },
              ),
            ],
          ),
          SizedBox(height: 10),
          Container(
            height: 50,
            padding: EdgeInsets.symmetric(
              vertical: 5,
              horizontal: 8,
            ),
            decoration: BoxDecoration(
              color: Colors.grey.shade200,
              borderRadius: BorderRadius.circular(5),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Icon(Icons.star),
                SizedBox(width: 10),
                Expanded(
                  child: TextField(
                    cursorColor: Colors.grey,
                    decoration: InputDecoration(
                      isDense: true,
                      contentPadding: EdgeInsets.zero,
                      border: InputBorder.none,
                      hintText: 'Container 和 TextField 结合',
                    ),
                  ),
                ),
              ],
            ),
          ),

          SizedBox(height: 10),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('简单的表单测试'),
        centerTitle: true,
        actions: [
          Stack(
            alignment: Alignment.topRight,
            children: [
              PopupMenuButton<int>(
                // child: Icon(Icons.more_horiz),
                icon: Icon(Icons.more_horiz),
                itemBuilder: (BuildContext context) {
                  return List.generate(
                    3,
                    (index) => PopupMenuItem(
                      child: Text('$index'),
                      value: index,
                    ),
                  );
                },
                onSelected: (value) => print(value),
              ),
            ],
          ),
        ],
      ),
      body: ListView(
        children: [
          _titleBuilder('DropdownButton'),
          _dropdownButtonBuilder(),
          _titleBuilder('CheckBox'),
          ..._checkboxBuilder(),
          _titleBuilder('Radio'),
          ..._radioBuilder(),
          _titleBuilder('Slider'),
          ..._sliderBuilder(),
          _titleBuilder('Switch'),
          ..._switchBuilder(),
          _titleBuilder('TextField'),
          _textFieldBuilder(),
        ],
      ),
    );
  }
}
